package com.plugin.gocqhttp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.plugin.gocqhttp.event.EventTypeAdaptHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Map;

/**
 * go - cqhttp 插件  QQ 消息转发
 *  https://docs.go-cqhttp.org/event/#%E7%A7%81%E8%81%8A%E6%B6%88%E6%81%AF
 *  https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E7%A7%81%E8%81%8A%E6%B6%88%E6%81%AF
 *  @author zehua
 */
@Controller
@Slf4j
public class GocqhttpController implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Collection<EventTypeAdaptHandler> eventTypeAdaptHandlerList;

    /**
     * go-cqhttp 服务端调用接口
     * @param request
     */
    @RequestMapping("requestmsg")
    @ResponseBody
    public void  reciveMsg(HttpServletRequest request) throws IOException {
        JSONObject jsonParam = getRequestJSONParam(request);
        log.debug("收到消息{}",jsonParam.toJSONString());
        for (EventTypeAdaptHandler eventTypeAdaptHandler : eventTypeAdaptHandlerList) {
            if (eventTypeAdaptHandler.suppert(jsonParam)){
                if (!jsonParam.toString().contains("heartbeat")){
                    log.info("【事件上报】 消息:{}",jsonParam.toString());
                }
                eventTypeAdaptHandler.handlerRequest(jsonParam);
                return;
            }
        }
    }

    private JSONObject getRequestJSONParam(HttpServletRequest request) throws IOException {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8")); // 获取输入流
            StringBuilder sb = new StringBuilder();         // 数据写入Stringbuilder
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            return JSON.parseObject(sb.toString());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        Map<String, EventTypeAdaptHandler> beansOfType = applicationContext.getBeansOfType(EventTypeAdaptHandler.class);
        Collection<EventTypeAdaptHandler> values = beansOfType.values();
        //TODO 接口排序 执行链
        this.eventTypeAdaptHandlerList= values ;
    }
}
